class ScrcpyInput {
    constructor(callback, videoElement, width, height, debug = false) {
        this.callback = callback
        this.width = width
        this.height = height
        this.debug = debug
        this.videoElement = videoElement  // 🔧 保存videoElement引用
        
        // 🔧 保存事件监听器引用以便后续清理
        this.eventListeners = []
        
        // 🔧 调用设置事件监听器方法
        this.setupEventListeners()
    }
    
    // 🆕 统一的坐标转换方法
    convertCoordinates(clientX, clientY, rect) {
        const local_x = clientX - rect.left;
        const local_y = clientY - rect.top;
        
        // 🔧 确保精确计算显示尺寸
        const videoDisplayWidth = rect.right - rect.left;
        const videoDisplayHeight = rect.bottom - rect.top;
        
        // 🔧 防止除零错误
        if (videoDisplayWidth <= 0 || videoDisplayHeight <= 0) {
            console.warn('⚠️ 视频显示尺寸异常:', { width: videoDisplayWidth, height: videoDisplayHeight });
            return { x: 0, y: 0, valid: false };
        }
        
        // 🔧 边界检查
        if (local_x < 0 || local_x > videoDisplayWidth || local_y < 0 || local_y > videoDisplayHeight) {
            if (this.debug) {
                console.warn('⚠️ 点击坐标超出视频边界:', {
                    点击位置: { x: local_x, y: local_y },
                    视频边界: { width: videoDisplayWidth, height: videoDisplayHeight }
                });
            }
            // 将坐标限制在边界内
            const clampedX = Math.max(0, Math.min(local_x, videoDisplayWidth));
            const clampedY = Math.max(0, Math.min(local_y, videoDisplayHeight));
            
            const mouseX = (clampedX / videoDisplayWidth) * this.width;
            const mouseY = (clampedY / videoDisplayHeight) * this.height;
            
            return { x: mouseX, y: mouseY, valid: true, clamped: true };
        }
        
        // 🔧 正常坐标转换
        const mouseX = (local_x / videoDisplayWidth) * this.width;
        const mouseY = (local_y / videoDisplayHeight) * this.height;
        
        if (this.debug) {
            // 🔧 获取视频元素的详细信息用于调试
            const rect = this.videoElement.getBoundingClientRect();
            console.log('🎯 坐标转换详情:', {
                原始位置: { x: clientX, y: clientY },
                本地位置: { x: local_x, y: local_y },
                视频显示尺寸: { width: videoDisplayWidth, height: videoDisplayHeight },
                设备目标尺寸: { width: this.width, height: this.height },
                缩放比例: { x: this.width / videoDisplayWidth, y: this.height / videoDisplayHeight },
                转换结果: { x: Math.round(mouseX), y: Math.round(mouseY) },
                视频元素信息: {
                    rect: { left: rect.left, top: rect.top, width: rect.width, height: rect.height },
                    id: this.videoElement.id || 'unknown',
                    className: this.videoElement.className || 'none'
                },
                组件状态: {
                    模式: this.videoElement.closest('.scrcpy-screen-with-permission')?.dataset.mode || 'unknown',
                    时间戳: new Date().toLocaleTimeString()
                }
            });
        }
        
        return { x: mouseX, y: mouseY, valid: true, clamped: false };
    }
    
    // 🔧 构造函数继续
    setupEventListeners() {
        let mouseX = null;
        let mouseY = null;
        let leftButtonIsPressed = false;
        let rightButtonIsPressed = false;

        // 🔧 将事件监听器函数保存为实例方法
        this.mouseDownHandler = (event) => {
            const rect = this.videoElement.getBoundingClientRect();

            if (this.videoElement.contains(event.target)) {
                if (event.button === 0) {
                    leftButtonIsPressed = true;

                    // 🔧 使用统一的坐标转换方法
                    const coords = this.convertCoordinates(event.clientX, event.clientY, rect);
                    
                    if (!coords.valid) {
                        console.warn('⚠️ 坐标转换失败，跳过点击事件');
                        return;
                    }
                    
                    mouseX = coords.x;
                    mouseY = coords.y;

                    // 🆕 添加调试信息
                    if (this.debug) {
                        console.log('🖱️ 鼠标按下 (左键):', {
                            转换结果: coords,
                            最终坐标: { x: Math.round(mouseX), y: Math.round(mouseY) }
                        })
                    }

                    let data = this.createTouchProtocolData(0, mouseX, mouseY, this.width, this.height, 0, 0, 65535);
                    this.callback(data);
                } else if (event.button === 2) {
                    rightButtonIsPressed = true;

                    // 🆕 添加调试信息
                    if (this.debug) {
                        console.log('🖱️ 鼠标按下 (右键) - 发送返回键')
                    }

                    this.sendKeyCode(event, 0, 4);
                    event.preventDefault();
                }
            }
        };

        // 🔧 将事件监听器函数保存为实例方法
        this.mouseUpHandler = (event) => {
            if (!leftButtonIsPressed) return;

            const rect = this.videoElement.getBoundingClientRect();
            const local_x = event.clientX - rect.left;
            const local_y = event.clientY - rect.top;

            if (event.button === 0) {
                leftButtonIsPressed = false;

                if (this.videoElement.contains(event.target)) {
                    // 🔧 使用统一的坐标转换方法
                    const coords = this.convertCoordinates(event.clientX, event.clientY, rect);
                    
                    if (coords.valid) {
                        mouseX = coords.x;
                        mouseY = coords.y;
                        
                        // 🆕 添加调试信息
                        if (this.debug) {
                            console.log('🖱️ 鼠标抬起 (左键):', {
                                转换结果: coords,
                                最终坐标: { x: Math.round(mouseX), y: Math.round(mouseY) }
                            })
                        }
                    }
                }
    
                let data = this.createTouchProtocolData(1, mouseX, mouseY, this.width, this.height, 0, 0, 0);
                this.callback(data);

            } else if (event.button === 2 && rightButtonIsPressed) {
                rightButtonIsPressed = false;

                                    this.sendKeyCode(event, 1, 4);
                event.preventDefault();
            }
        };

        // 🔧 将事件监听器函数保存为实例方法
        this.mouseMoveHandler = (event) => {
            if (!leftButtonIsPressed) return;

            const rect = this.videoElement.getBoundingClientRect();

            if (this.videoElement.contains(event.target)) {
                // 🔧 使用统一的坐标转换方法
                const coords = this.convertCoordinates(event.clientX, event.clientY, rect);
                
                if (!coords.valid) {
                    console.warn('⚠️ 鼠标移动坐标转换失败');
                    return;
                }
                
                mouseX = coords.x;
                mouseY = coords.y;

                // 🆕 添加调试信息
                if (this.debug) {
                    console.log('🖱️ 鼠标移动:', {
                        转换结果: coords,
                        最终坐标: { x: Math.round(mouseX), y: Math.round(mouseY) }
                    })
                }

                let data = this.createTouchProtocolData(2, mouseX, mouseY, this.width, this.height, 0, 0, 65535);
                this.callback(data);
            }
        };

        // 🔧 将事件监听器函数保存为实例方法
        this.contextMenuHandler = (event) => {
            event.preventDefault();
        };

        // 🔧 将事件监听器函数保存为实例方法
        this.wheelHandler = (event) => {
            const hScroll = event.deltaX;
            const vScroll = event.deltaY;
            const deltaMode = event.deltaMode;
            const deltaZ = event.deltaZ;
            const clientX = event.clientX;
            const clientY = event.clientY;
            const button = event.button;

            const rect = this.videoElement.getBoundingClientRect();
            const relativeX = clientX - rect.left;
            const relativeY = clientY - rect.top;
            const width = rect.right - rect.left;
            const height = rect.bottom - rect.top;

            // switch (deltaMode) {
            //     case WheelEvent.DOM_DELTA_PIXEL:
            //         deltaModeValue.textContent = 'pixel';
            //         break;
            //     case WheelEvent.DOM_DELTA_LINE:
            //         deltaModeValue.textContent = 'row';
            //         break;
            //     case WheelEvent.DOM_DELTA_PAGE:
            //         deltaModeValue.textContent = 'page';
            //         break;
            //     default:
            //         deltaModeValue.textContent = 'unknown';
            // }
            let data = this.createScrollProtocolData(relativeX, relativeY, width, height, hScroll, vScroll, button);
            this.callback(data);
        };

        // 🔧 将事件监听器函数保存为实例方法
        this.keydownHandler = async (event) => {
            // 🆕 处理剪贴板快捷键
            if (event.ctrlKey) {
                if (event.key === 'c' || event.key === 'C') {
                    console.log('⌨️ Ctrl+C: 复制');
                    event.preventDefault();
                    this.handleCopy();
                    return;
                } else if (event.key === 'v' || event.key === 'V') {
                    console.log('⌨️ Ctrl+V: 粘贴');
                    event.preventDefault();
                    await this.handlePaste();
                    return;
                }
            }

            // 🆕 处理常规按键
            const androidKeyCode = this.mapToAndroidKeyCode(event);
            if (androidKeyCode !== null) {
                event.preventDefault(); // 阻止默认行为
                this.sendKeyCode(event, 0, androidKeyCode);
                
                if (this.debug) {
                    console.log('⌨️ 按键按下:', {
                        key: event.key,
                        code: event.code,
                        androidKeyCode: androidKeyCode
                    });
                }
            } else {
                // 🆕 对于未映射的按键，如果是可打印字符，发送文本输入
                if (event.key.length === 1 && !event.ctrlKey && !event.altKey && !event.metaKey) {
                    event.preventDefault();
                    this.sendText(event.key);
                    
                    if (this.debug) {
                        console.log('📝 发送文本字符:', event.key);
                    }
                } else {
                    console.log(`❓ 未映射的按键: ${event.code} (${event.key})`);
                }
            }
        };

        // 🔧 将事件监听器函数保存为实例方法
        this.keyupHandler = async (event) => {
            // 🆕 只有映射到Android按键的才需要发送释放事件
            const androidKeyCode = this.mapToAndroidKeyCode(event);
            if (androidKeyCode !== null) {
                event.preventDefault(); // 阻止默认行为
                this.sendKeyCode(event, 1, androidKeyCode);
                
                if (this.debug) {
                    console.log('⌨️ 按键释放:', {
                        key: event.key,
                        code: event.code,
                        androidKeyCode: androidKeyCode
                    });
                }
            }
            // 🆕 对于文本字符和剪贴板快捷键，不需要发送释放事件
        };

        // 🔧 添加事件监听器并记录
        document.addEventListener('mousedown', this.mouseDownHandler)
        document.addEventListener('mouseup', this.mouseUpHandler)
        document.addEventListener('mousemove', this.mouseMoveHandler)
        this.videoElement.addEventListener('contextmenu', this.contextMenuHandler)
        this.videoElement.addEventListener('wheel', this.wheelHandler)
        this.videoElement.addEventListener('keydown', this.keydownHandler)
        this.videoElement.addEventListener('keyup', this.keyupHandler)
        
        // 🔧 记录监听器信息以便后续清理
        this.eventListeners = [
            { target: document, type: 'mousedown', handler: this.mouseDownHandler },
            { target: document, type: 'mouseup', handler: this.mouseUpHandler },
            { target: document, type: 'mousemove', handler: this.mouseMoveHandler },
            { target: this.videoElement, type: 'contextmenu', handler: this.contextMenuHandler },
            { target: this.videoElement, type: 'wheel', handler: this.wheelHandler },
            { target: this.videoElement, type: 'keydown', handler: this.keydownHandler },
            { target: this.videoElement, type: 'keyup', handler: this.keyupHandler }
        ]
    }

    resizeScreen(width, height) {
        this.width = width;
        this.height = height;
    }

    mapToAndroidKeyCode(event) {
        const codeToAndroidKeyCode = {
            'KeyA': 29,  // KEYCODE_A
            'KeyB': 30,  // KEYCODE_B
            'KeyC': 31,  // KEYCODE_C
            'KeyD': 32,  // KEYCODE_D
            'KeyE': 33,  // KEYCODE_E
            'KeyF': 34,  // KEYCODE_F
            'KeyG': 35,  // KEYCODE_G
            'KeyH': 36,  // KEYCODE_H
            'KeyI': 37,  // KEYCODE_I
            'KeyJ': 38,  // KEYCODE_J
            'KeyK': 39,  // KEYCODE_K
            'KeyL': 40,  // KEYCODE_L
            'KeyM': 41,  // KEYCODE_M
            'KeyN': 42,  // KEYCODE_N
            'KeyO': 43,  // KEYCODE_O
            'KeyP': 44,  // KEYCODE_P
            'KeyQ': 45,  // KEYCODE_Q
            'KeyR': 46,  // KEYCODE_R
            'KeyS': 47,  // KEYCODE_S
            'KeyT': 48,  // KEYCODE_T
            'KeyU': 49,  // KEYCODE_U
            'KeyV': 50,  // KEYCODE_V
            'KeyW': 51,  // KEYCODE_W
            'KeyX': 52,  // KEYCODE_X
            'KeyY': 53,  // KEYCODE_Y
            'KeyZ': 54,  // KEYCODE_Z

            'Digit0': 7,   // KEYCODE_0
            'Digit1': 8,   // KEYCODE_1
            'Digit2': 9,   // KEYCODE_2
            'Digit3': 10,  // KEYCODE_3
            'Digit4': 11,  // KEYCODE_4
            'Digit5': 12,  // KEYCODE_5
            'Digit6': 13,  // KEYCODE_6
            'Digit7': 14,  // KEYCODE_7
            'Digit8': 15,  // KEYCODE_8
            'Digit9': 16,  // KEYCODE_9

            'Enter': 66,       // KEYCODE_ENTER
            'Backspace': 67,   // KEYCODE_DEL
            'Tab': 61,         // KEYCODE_TAB
            'Space': 62,       // KEYCODE_SPACE
            'Escape': 111,     // KEYCODE_ESCAPE
            'CapsLock': 115,   // KEYCODE_CAPS_LOCK
            'NumLock': 143,    // KEYCODE_NUM_LOCK
            'ScrollLock': 116, // KEYCODE_SCROLL_LOCK

            'ArrowUp': 19,     // KEYCODE_DPAD_UP
            'ArrowDown': 20,   // KEYCODE_DPAD_DOWN
            'ArrowLeft': 21,   // KEYCODE_DPAD_LEFT
            'ArrowRight': 22,  // KEYCODE_DPAD_RIGHT

            'ShiftLeft': 59,   // KEYCODE_SHIFT_LEFT
            'ShiftRight': 60,  // KEYCODE_SHIFT_RIGHT
            'ControlLeft': 113,// KEYCODE_CTRL_LEFT
            'ControlRight': 114,// KEYCODE_CTRL_RIGHT
            'AltLeft': 57,     // KEYCODE_ALT_LEFT
            'AltRight': 58,    // KEYCODE_ALT_RIGHT
            'MetaLeft': 117,   // KEYCODE_META_LEFT
            'MetaRight': 118,  // KEYCODE_META_RIGHT

            'Numpad0': 144,    // KEYCODE_NUMPAD_0
            'Numpad1': 145,    // KEYCODE_NUMPAD_1
            'Numpad2': 146,    // KEYCODE_NUMPAD_2
            'Numpad3': 147,    // KEYCODE_NUMPAD_3
            'Numpad4': 148,    // KEYCODE_NUMPAD_4
            'Numpad5': 149,    // KEYCODE_NUMPAD_5
            'Numpad6': 150,    // KEYCODE_NUMPAD_6
            'Numpad7': 151,    // KEYCODE_NUMPAD_7
            'Numpad8': 152,    // KEYCODE_NUMPAD_8
            'Numpad9': 153,    // KEYCODE_NUMPAD_9
            'NumpadEnter': 160,// KEYCODE_NUMPAD_ENTER
            'NumpadAdd': 157,  // KEYCODE_NUMPAD_ADD
            'NumpadSubtract': 156, // KEYCODE_NUMPAD_SUBTRACT
            'NumpadMultiply': 155, // KEYCODE_NUMPAD_MULTIPLY
            'NumpadDivide': 154,   // KEYCODE_NUMPAD_DIVIDE

            'F1': 131,  // KEYCODE_F1
            'F2': 132,  // KEYCODE_F2
            'F3': 133,  // KEYCODE_F3
            'F4': 134,  // KEYCODE_F4
            'F5': 135,  // KEYCODE_F5
            'F6': 136,  // KEYCODE_F6
            'F7': 137,  // KEYCODE_F7
            'F8': 138,  // KEYCODE_F8
            'F9': 139,  // KEYCODE_F9
            'F10': 140, // KEYCODE_F10
            'F11': 141, // KEYCODE_F11
            'F12': 142, // KEYCODE_F12

            'Insert': 124,     // KEYCODE_INSERT
            'Delete': 112,     // KEYCODE_FORWARD_DEL
            'Home': 122,       // KEYCODE_MOVE_HOME
            'End': 123,        // KEYCODE_MOVE_END
            'PageUp': 92,      // KEYCODE_PAGE_UP
            'PageDown': 93,    // KEYCODE_PAGE_DOWN

            // 🆕 Android系统键映射
            'Browser Back': 4,        // KEYCODE_BACK (Android返回键)
            'AudioVolumeUp': 24,     // KEYCODE_VOLUME_UP
            'AudioVolumeDown': 25,   // KEYCODE_VOLUME_DOWN
            'AudioVolumeMute': 164,  // KEYCODE_VOLUME_MUTE
            'ContextMenu': 82,       // KEYCODE_MENU (Android菜单键)
            
            // 🆕 特殊快捷键映射 - 映射到Android系统键
            'F7': 3,    // 映射F7到HOME键 (KEYCODE_HOME)
            'F8': 4,    // 映射F8到BACK键 (KEYCODE_BACK) 
            'F9': 82,   // 映射F9到MENU键 (KEYCODE_MENU)
            'F10': 187, // 映射F10到APP_SWITCH键 (最近任务)
        };

        return codeToAndroidKeyCode[event.code] || null;
    }

    sendKeyCode(keyevent, action, keycode) {
        const capsLockState = keyevent.getModifierState('CapsLock');
        const numLockState = keyevent.getModifierState('NumLock');
        const scrollLockState = keyevent.getModifierState('ScrollLock');

        let metakey = 0;
        if (keyevent.shiftKey) {
            metakey |= 0x40;
        }
        if (keyevent.ctrlKey) {
            metakey |= 0x2000;
        }
        if (keyevent.altKey) {
            metakey |= 0x10;
        }
        if (keyevent.metaKey) {
            metakey |= 0x20000;
        }
        if (capsLockState) {
            metakey |= 0x100000;
        }
        if (numLockState) {
            metakey |= 0x200000;
        }
        // if(scrollLockState)
        // {
        //     metakey |= 0x400000;
        // }
        let data = this.createKeyProtocolData(action, keycode, keyevent.repeat, metakey);
        this.callback(data);
    }

    createTouchProtocolData(action, x, y, width, height, actionButton, buttons, pressure) {
        const type = 2; // touch event
        
        // 🆕 添加调试信息
        if (this.debug) {
            console.log('🎯 创建触摸协议数据:', {
                action: action,
                x: Math.round(x),
                y: Math.round(y),
                width: width,
                height: height,
                pressure: pressure
            })
        }

        const buffer = new ArrayBuffer(1 + 1 + 8 + 4 + 4 + 2 + 2 + 2 + 4 + 4);
        const view = new DataView(buffer);

        let offset = 0;

        view.setUint8(offset, type);
        offset += 1;

        view.setUint8(offset, action);
        offset += 1;

        view.setUint8(offset, 0xff);
        offset += 1;
        view.setUint8(offset, 0xff);
        offset += 1;
        view.setUint8(offset, 0xff);
        offset += 1;
        view.setUint8(offset, 0xff);
        offset += 1;
        view.setUint8(offset, 0xff);
        offset += 1;
        view.setUint8(offset, 0xff);
        offset += 1;
        view.setUint8(offset, 0xff);
        offset += 1;
        view.setUint8(offset, 0xfd);
        offset += 1;

        view.setInt32(offset, x, false);
        offset += 4;
        view.setInt32(offset, y, false);
        offset += 4;
        view.setUint16(offset, width, false);
        offset += 2;
        view.setUint16(offset, height, false);
        offset += 2;

        view.setInt16(offset, pressure, false);
        offset += 2;

        view.setInt32(offset, actionButton, false);
        offset += 4;

        view.setInt32(offset, buttons, false);

        return buffer;
    }

    createKeyProtocolData(action, keycode, repeat, metaState) {
        const type = 0; // key event

        const buffer = new ArrayBuffer(1 + 1 + 4 + 4 + 4);
        const view = new DataView(buffer);

        let offset = 0;

        view.setUint8(offset, type);
        offset += 1;

        view.setUint8(offset, action);
        offset += 1;

        view.setInt32(offset, keycode, false);
        offset += 4;
        view.setInt32(offset, repeat, false);
        offset += 4;
        view.setInt32(offset, metaState, false);

        return buffer;
    }

    createScrollProtocolData(x, y, width, height, hScroll, vScroll, button) {
        const type = 3; // scroll event

        const buffer = new ArrayBuffer(1 + 4 + 4 + 2 + 2 + 2 + 2 + 4);
        const view = new DataView(buffer);

        let offset = 0;
        view.setUint8(offset, type);
        offset += 1;

        view.setInt32(offset, x, false);
        offset += 4;
        view.setInt32(offset, y, false);
        offset += 4;
        view.setUint16(offset, width, false);
        offset += 2;
        view.setUint16(offset, height, false);
        offset += 2;

        view.setInt16(offset, hScroll, false);
        offset += 2;
        view.setInt16(offset, vScroll, false);
        offset += 2;

        view.setInt32(offset, button, false);

        return buffer;
    }

    createScreenProtocolData(action) {
        const type = 4; // Screen off/on event

        const buffer = new ArrayBuffer(1 + 1);
        const view = new DataView(buffer);

        let offset = 0;
        view.setUint8(offset, type);
        offset += 1;

        view.setUint8(offset, action);

        return buffer;
    }

    createPowerProtocolData(action) {
        const type = 7; // Screen Power off/on event

        const buffer = new ArrayBuffer(1 + 1);
        const view = new DataView(buffer);

        let offset = 0;
        view.setUint8(offset, type);
        offset += 1;

        view.setUint8(offset, action);

        return buffer;
    }

    // 🆕 创建文本输入协议数据
    createTextProtocolData(text) {
        const type = 1; // text input event
        const textBytes = new TextEncoder().encode(text);
        
        const buffer = new ArrayBuffer(1 + 4 + textBytes.length);
        const view = new DataView(buffer);

        let offset = 0;
        view.setUint8(offset, type);
        offset += 1;
        
        view.setInt32(offset, textBytes.length, false);
        offset += 4;
        
        // 写入文本字节
        new Uint8Array(buffer, offset).set(textBytes);

        return buffer;
    }

    // 🆕 创建剪贴板设置协议数据
    createSetClipboardProtocolData(text, paste = false) {
        const type = 9; // set clipboard event
        const textBytes = new TextEncoder().encode(text);
        
        const buffer = new ArrayBuffer(1 + 1 + 4 + textBytes.length);
        const view = new DataView(buffer);

        let offset = 0;
        view.setUint8(offset, type);
        offset += 1;
        
        view.setUint8(offset, paste ? 1 : 0); // paste flag
        offset += 1;
        
        view.setInt32(offset, textBytes.length, false);
        offset += 4;
        
        // 写入文本字节
        new Uint8Array(buffer, offset).set(textBytes);

        return buffer;
    }

    // 🆕 创建获取剪贴板协议数据
    createGetClipboardProtocolData() {
        const type = 8; // get clipboard event

        const buffer = new ArrayBuffer(1);
        const view = new DataView(buffer);

        view.setUint8(0, type);

        return buffer;
    }

    add_debug_item(text) {
        const p = document.createElement('p');
        p.textContent = text;
        const span = document.createElement('span');
        span.textContent = '0';
        p.appendChild(span);
        document.body.appendChild(p);
        return span;
    }

    screen_on_off(action) {
        let data = null;
        data = this.createScreenProtocolData(action);
        this.callback(data)
    }

    // 🆕 发送文本输入
    sendText(text) {
        if (this.debug) {
            console.log('📝 发送文本输入:', text);
        }
        const data = this.createTextProtocolData(text);
        this.callback(data);
    }

    // 🆕 设置设备剪贴板
    setClipboard(text, paste = false) {
        if (this.debug) {
            console.log('📋 设置剪贴板:', text, paste ? '(并粘贴)' : '');
        }
        const data = this.createSetClipboardProtocolData(text, paste);
        this.callback(data);
    }

    // 🆕 获取设备剪贴板
    getClipboard() {
        if (this.debug) {
            console.log('📋 请求获取剪贴板');
        }
        const data = this.createGetClipboardProtocolData();
        this.callback(data);
    }

    // 🆕 检查剪贴板API是否可用
    isClipboardAPISupported() {
        return navigator.clipboard && 
               typeof navigator.clipboard.readText === 'function' && 
               typeof navigator.clipboard.writeText === 'function';
    }

    // 🆕 处理剪贴板粘贴 (Ctrl+V)
    async handlePaste() {
        try {
            // 检查剪贴板API是否可用
            if (!this.isClipboardAPISupported()) {
                console.warn('⚠️ 剪贴板API不可用 (需要HTTPS或localhost环境)');
                
                // 降级方案：提示用户手动输入
                const userInput = prompt('剪贴板API不可用，请手动输入要粘贴的内容:');
                if (userInput && userInput.trim()) {
                    console.log('📋 用户手动输入内容:', userInput);
                    this.setClipboard(userInput, true); // 设置并粘贴
                } else {
                    console.log('❌ 用户取消了手动输入');
                }
                return;
            }

            // 使用剪贴板API
            const clipboardData = await navigator.clipboard.readText();
            if (clipboardData && clipboardData.trim()) {
                console.log('📋 粘贴剪贴板内容:', clipboardData);
                this.setClipboard(clipboardData, true); // 设置并粘贴
            } else {
                console.warn('⚠️ 剪贴板为空');
            }
        } catch (err) {
            console.error('❌ 读取剪贴板失败:', err);
            
            // 降级方案：出错时也提供手动输入
            try {
                const userInput = prompt('剪贴板读取失败，请手动输入要粘贴的内容:');
                if (userInput && userInput.trim()) {
                    console.log('📋 降级到用户手动输入:', userInput);
                    this.setClipboard(userInput, true);
                }
            } catch (fallbackErr) {
                console.error('❌ 降级方案也失败了:', fallbackErr);
            }
        }
    }

    // 🆕 处理剪贴板复制 (Ctrl+C)
    handleCopy() {
        if (!this.isClipboardAPISupported()) {
            console.warn('⚠️ 剪贴板API不可用，只能获取设备剪贴板到控制台');
        }
        
        console.log('📋 请求复制（获取设备剪贴板）');
        this.getClipboard();
    }

    // 🆕 Android系统键快捷方法
    sendHomeKey() {
        if (this.debug) {
            console.log('🏠 发送HOME键');
        }
        const data = this.createKeyProtocolData(0, 3, 0, 0); // DOWN
        this.callback(data);
        const data2 = this.createKeyProtocolData(1, 3, 0, 0); // UP
        this.callback(data2);
    }

    sendBackKey() {
        if (this.debug) {
            console.log('⬅️ 发送BACK键');
        }
        const data = this.createKeyProtocolData(0, 4, 0, 0); // DOWN
        this.callback(data);
        const data2 = this.createKeyProtocolData(1, 4, 0, 0); // UP
        this.callback(data2);
    }

    sendMenuKey() {
        if (this.debug) {
            console.log('📋 发送MENU键');
        }
        const data = this.createKeyProtocolData(0, 82, 0, 0); // DOWN
        this.callback(data);
        const data2 = this.createKeyProtocolData(1, 82, 0, 0); // UP
        this.callback(data2);
    }

    sendRecentAppsKey() {
        if (this.debug) {
            console.log('📱 发送最近应用键');
        }
        const data = this.createKeyProtocolData(0, 187, 0, 0); // DOWN
        this.callback(data);
        const data2 = this.createKeyProtocolData(1, 187, 0, 0); // UP
        this.callback(data2);
    }

    sendVolumeUpKey() {
        if (this.debug) {
            console.log('🔊 发送音量+键');
        }
        const data = this.createKeyProtocolData(0, 24, 0, 0); // DOWN
        this.callback(data);
        const data2 = this.createKeyProtocolData(1, 24, 0, 0); // UP
        this.callback(data2);
    }

    sendVolumeDownKey() {
        if (this.debug) {
            console.log('🔉 发送音量-键');
        }
        const data = this.createKeyProtocolData(0, 25, 0, 0); // DOWN
        this.callback(data);
        const data2 = this.createKeyProtocolData(1, 25, 0, 0); // UP
        this.callback(data2);
    }

    sendPowerKey() {
        if (this.debug) {
            console.log('⚡ 发送电源键');
        }
        const data = this.createKeyProtocolData(0, 26, 0, 0); // DOWN
        this.callback(data);
        const data2 = this.createKeyProtocolData(1, 26, 0, 0); // UP
        this.callback(data2);
    }

    // 🔧 添加清理方法
    cleanup() {
        if (this.debug) {
            console.log('🧹 清理ScrcpyInput事件监听器')
        }
        
        this.eventListeners.forEach(({ target, type, handler }) => {
            target.removeEventListener(type, handler)
        })
        
        this.eventListeners = []
        this.videoElement = null
        
        if (this.debug) {
            console.log('✅ ScrcpyInput清理完成')
        }
    }
}

// 🆕 导出ScrcpyInput到全局对象
window.ScrcpyInput = ScrcpyInput;